package com.china08.yxyapi.api.manage.tec.teaching.homework.worklist.workinfo.report.lookanalyse;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.homework.HomeworkKnowReport;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskQues;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReport;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReportQues;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.homework.HomeworkKnowReportRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportRepository;
import com.china08.yxyapi.util.DateUtils;

/**
 * 家长端作业系统 查看分析
 */
@CrossOrigin
@RestController
public class HomeworkReportAnalyseController extends YxyApiBaseController {

    @Autowired
    private HomeworkTaskReportQuesRepository homeworkTaskReportQuesRepository;

    @Autowired
    private HomeworkTaskReportRepository homeworkTaskReportRepository;

    @Autowired
    private HomeworkKnowReportRepository homeworkKnowReportRepository;

    @Autowired
    private HomeworkTaskQuesRepository homeworkTaskQuesRepository;

    @ResponseBody
    @RequestMapping(value = "/api_yw/manage/tec/teaching/homework/worklist/workinfo/report/analyse", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel precess(@RequestBody ReqModel req, RespModel respModel) {
        String studentId = req.studentId;
        String taskId = req.taskId;
        // 将查看分析页面的标题之类的查出来（标题，姓名,所在班级，作业用时，正确率,班级排名）
        HomeworkTaskReport homeworkTaskReport = homeworkTaskReportRepository.findByStudentIdAndTaskId(studentId,
                taskId);
        String classId = null;
        if (homeworkTaskReport != null) {
            respModel.title = homeworkTaskReport.getTitle();
            respModel.studentNick = homeworkTaskReport.getStudentNick();
            respModel.className = homeworkTaskReport.getClassName();
            classId = homeworkTaskReport.getClassId();
            respModel.duration = DateUtils.getDurationDateByDurationCount(homeworkTaskReport.getDuration() * 1000);

            // 将double类型的数据保存到小数点的后两位
            DecimalFormat df = new DecimalFormat("######0.0");
            respModel.rightRate = Double.parseDouble(df.format(homeworkTaskReport.getRightRate()));
            // 将查看分析页面的作答情况的试题查出来
            List<HomeworkTaskReportQues> homeworkTaskReportQuesLst = homeworkTaskReportQuesRepository
                    .findByTaskIdAndStudentIdOrderByOrderAsc(taskId, studentId);
            List<HomeworkTaskReportQuesModel> homeworkTaskReportQuestLst = new ArrayList<HomeworkTaskReportQuesModel>();
            HomeworkTaskReportQuesModel homeworkTaskReportQuesModel = null;
            for (HomeworkTaskReportQues homeworkTaskReportQues : homeworkTaskReportQuesLst) {
                homeworkTaskReportQuesModel = new HomeworkTaskReportQuesModel();
                homeworkTaskReportQuesModel.order = homeworkTaskReportQues.getOrder();
                homeworkTaskReportQuesModel.difficultyLevel = homeworkTaskReportQues.getDifficultyLevel();
                homeworkTaskReportQuesModel.passed = homeworkTaskReportQues.getPassed();
                homeworkTaskReportQuesModel.knowNameLst = homeworkTaskReportQues.getKnowNameLst();
                homeworkTaskReportQuesModel.answerOfMy = homeworkTaskReportQues.getAnswerOfMy();
                homeworkTaskReportQuesModel.mark = homeworkTaskReportQues.getMark();
                homeworkTaskReportQuesModel.quesType = homeworkTaskReportQues.getQuestionType();
                homeworkTaskReportQuestLst.add(homeworkTaskReportQuesModel);
            }
            respModel.homeworkTaskReportQuestLst = homeworkTaskReportQuestLst;
            // 将个人情况查出来
            List<HomeworkKnowReport> homeworkKnowReport = homeworkKnowReportRepository
                    .findByStudentIdAndTaskId(studentId, taskId);
            List<String> knowNamesList = new ArrayList<String>();
            // 知识点ids
            // 知识点掌握情况
            List<HomeworkTaskQues> homeworkTaskQuesLst = homeworkTaskQuesRepository.findByTaskId(taskId);
            List<Integer> knowIdsList = new ArrayList<Integer>();
            for (HomeworkTaskQues ques : homeworkTaskQuesLst) {
                if (ques.getQuesType() == null || ques.getQuesType().equals("2")) {
                    continue;
                }
                knowIdsList.addAll(ques.getKnowId());// 将每个知识点的id获取到并且添加到数组
                knowNamesList.addAll(ques.getKnowName());
                // to do
            }
            // 知识点name进行去重
            for (int i = 0; i < knowNamesList.size() - 1; i++) {
                for (int j = knowNamesList.size() - 1; j > i; j--) {
                    if (knowNamesList.get(j).equals(knowNamesList.get(i))) {
                        knowNamesList.remove(j);
                    }
                }
            }
            // 知识点id去重
            for (int i = 0; i < knowIdsList.size() - 1; i++) {
                for (int j = knowIdsList.size() - 1; j > i; j--) {
                    if (knowIdsList.get(j).equals(knowIdsList.get(i))) {
                        knowIdsList.remove(j);
                    }
                }
            }
            // 当前学生在当前任务中的所有知识点的报告列表
            List<Long> studentrate = new ArrayList<Long>();
            for (Integer knowIds : knowIdsList) {
                // 查出每个知识点下的个人的掌握率
                HomeworkKnowReport oneManOneKnowHomeworkKnowReport = homeworkKnowReportRepository
                        .findByStudentIdAndTaskIdAndKnowId(studentId, taskId, knowIds);
                if (oneManOneKnowHomeworkKnowReport != null) {
                    studentrate.add(oneManOneKnowHomeworkKnowReport.getRate().longValue());
                } else {
                    studentrate.add(0l);
                }
            }
            // 3.通过班级id获取当前班级的所有的学生答题记录
            List<HomeworkKnowReport> homeworkKnowReports = homeworkKnowReportRepository.findByClassIdAndTaskId(classId,
                    taskId);
            // 4.将班级id获取当前班级的所有的学生答题记录根据知识点id进行分组
            // 获取每个知识点总共的掌握率
            Map<Object, Double> result = homeworkKnowReports.parallelStream().filter(p -> p.getKnowId() != null)
                    .collect(Collectors.groupingBy(p -> p.getKnowId(), Collectors.summingDouble(p -> p.getRate())));
            // 获取每个知识点出现的次数
            Map<Object, Integer> resultInt = homeworkKnowReports.parallelStream().filter(p -> p.getKnowId() != null)
                    .collect(Collectors.groupingBy(p -> p.getKnowId(), Collectors.summingInt(p -> 1)));
            // 求出每个班级每个知识点的平均掌握率
            List<Long> classrate = new ArrayList<Long>();
            for (Integer knowId : knowIdsList) {
                for (Object key : result.keySet()) {
                    if ((int) key == knowId) {
                        for (Object key2 : resultInt.keySet()) {
                            if (key2 == key) {
                                // 5. 获取每个知识点总共的掌握率除以获取每个知识点出现的次数==班级掌握率
                                Double classRate = result.get(key) / resultInt.get(key2);
                                // 6.将每个知识点的班级掌握率依次封装在classrate数组里
                                classrate.add(classRate.longValue());
                            }
                        }

                    }
                }
            }
            // 封装知识点
            respModel.knowNamelList = knowNamesList;
            // 个人掌握率
            respModel.studentrate = studentrate;
            // 班级掌握率
            respModel.classrate = classrate;
        }
        return respModel;
    }

    protected static class ReqModel extends YxyApiReqModel {
        // 学生Id
        public String studentId;
        // 任务Id
        public String taskId;
    }

    public class HomeworkTaskReportQuesModel {
        // 题号
        public Integer order;
        // 难度级别:1-易,2-中,3-难
        public Integer difficultyLevel;
        // 是否正确 0-错误 , 1-正确 ,2-半对 20% ,3-半对 30% ,4-半对 80%
        public Integer passed;
        // 知识点:Name
        public List<String> knowNameLst;
        // 我的回答
        public String answerOfMy;
        // 试题类型
        public String quesType;
        // 得分
        public Integer mark;
    }

    protected static class RespModel extends YxyApiRespModel {
        // 做题情况列表
        public List<HomeworkTaskReportQuesModel> homeworkTaskReportQuestLst;
        // 查看分析页面的标题
        public String title;
        // 学生:名称
        public String studentNick;
        // 查看分析页面的所在班级;
        public String className;
        // 查看分析页面的作业用时
        public String duration;
        // 查看分析页面的正确率
        public Double rightRate;
        // 知识点
        public List<String> knowNamelList;
        // 个人掌握率
        public List<Long> studentrate;
        // 班级掌握率
        public List<Long> classrate;
    }
}
